<template>
  <base-modal :title="$t('department.modifyProviderPanel.title')" width="480px" :show.sync="visible" @close="close">
    <form-view :fields="formFields" :value="provider"></form-view>
    <div class="provider-area">
      <div class="provider-area-label">{{$t('department.modifyProviderPanel.scope')}}</div>
      <div class="user-tag" @click="chooseArea">
        <template v-if="selectedAll.length">
          <el-tag
            v-for="(item,index) in selectedAll"
            :key="item.userId"
            closable
            type="info"
            @close="removeUser(index)">
            <img :src="item.logo || item.head || defaultAvatar">
            <template v-if="isOpenData && item.staffId">
              <open-data :openid="item.staffId"></open-data>
            </template>
            <template v-else>{{item.name || item.displayName}}</template>
          </el-tag>
        </template>
        <template v-else>
          <span class="placeholder">{{$t('common.base.pleaseSelect')}}</span>
        </template>
      </div>
    </div>
    <div class="dialog-footer" slot="footer">
      <el-button @click="close">{{$t('common.base.cancel')}}</el-button>
      <el-button native-type="submit" type="primary" @click="submit" :disabled="disabled">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* utils */
import { isOpenData } from '@src/util/platform';
import * as FormUtil from '@form/util';
import { getOssUrl } from '@src/util/assets'
/* api */
import { getProviderByType, saveProviderByType } from '@src/api/serviceProviderApi';
const defaultAvatar = getOssUrl('/avatar.png');
export default {
  name: 'modify-provider-panel',
  data() {
    return {
      isOpenData,
      visible: false,
      provider: {},
      formFields: [
        { displayName: this.$t('common.fields.providerCode.displayName'), fieldName: 'providerCode', formType:'text', isSystem: 1 },
        { displayName: this.$t('common.fields.providerName.displayName'), fieldName: 'providerName', formType:'text', isSystem: 1 },
        { displayName: this.$t('common.fields.contact.displayName'), fieldName: 'contacts', formType:'text', isSystem: 1 },
        { displayName: this.$t('common.fields.contactNumber.displayName'), fieldName: 'providerPhone', formType:'text', isSystem: 1 },
      ],
      disabled: false,
      providerId: '', // 租户服务商ID
      selectedAll: [], // 服务商所选的部门h和用户
      defaultAvatar,
    }
  },
  methods: {
    async open(provider) {
      this.providerId = provider?.id;
      this.provider = FormUtil.initialize(this.formFields, provider || {});
      await this.searchDept(); // 查询服务商信息
      this.visible = true;
    },
    close() {
      this.visible = false;
    },
    // 弹框人员选择组件去选择部门和人员
    chooseArea() {
      this.$fast.select.multi.departmentAndUser({
        title: this.$t('department.modifyProviderPanel.selectUser'),
        showServiceProvider: false,
        isCanChooseDepartment: false,
        isShowSearchServiceProviderUsers: false, // 是否显示搜索 服务商人员列表
        mode: 'filter',
        selectedAll: this.selectedAll,
        max: -1,
        isTag: true,
      }).then(result => {
        if(result.status === 0) {
          this.selectedAll = result?.data?.all || []
        }
      }).catch(err => {
        console.error(err)
      })
    },
    // 移除所选的人员或部门
    removeUser(index){
       this.selectedAll.splice(index, 1);
    },
    // 查询服务商的部门和人员
    async searchDept() {
      try {
        let res = await getProviderByType({ objId: this.providerId, type: 1 });
        if(res.status === 0) {
          this.selectedAll = res.data|| [];
        }
      } catch (e) {
        console.warn(e)
      }
    },
    async submit() {
      try {
        let paramList = this.selectedAll.map(item => {
          return {
            id: item.userId || item.id,
            typeId: item?.typeId || ''
          }
        })
        let data = {
          objectId: this.providerId,
          type: 1, //（0团队1服务商）
          paramList,
        }
        let result = await saveProviderByType(data)
        let suc = result.success && result.data;
        this.$platform.notification({
          type: suc ? 'success' : 'error',
          title: `${this.$t('common.base.edit')}${suc ? this.$t('common.base.success') : this.$t('common.base.fail')}`,
          message: suc ? null : result?.message
        });
        this.visible = false;
        this.$emit('refresh')
      } catch (e) {
        console.warn(e)
      }
    },
  },
}
</script>

<style scoped lang="scss">
.provider-area {
  padding: 3px 20px 24px;
  display: flex;
  &-label {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    line-height: 20px;
    width: 98px;
    margin: 0 10px 0 0;
    color: #595959;
    word-break: break-all;
  }
  .user-tag {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex-grow: 1;
    justify-content: flex-start;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #e0e1e2;
    padding: 5px 12px;
    min-height: 32px;
    cursor: pointer;
    .el-tag {
      margin: 0 12px 5px 0
    }
    .placeholder {
      font-size: 14px;
      font-weight: 400;
      color: #BFBFBF;
      line-height: 22px;
    }
    img {
      border-radius: 50%;
      width: 24px;
      height: 24px;
      margin-right: 4px;
    }
  }
}
</style>
<style lang="scss">
.base-select-user-select-content-multi .base-select-user-filter{
  z-index: 1000;
}
</style>